<?php

class Domain_Token {

    public function create($info) {
        $userToken = DI()->helper->createRandStr(12);
        DI()->cache->set("userInfo:" . $userToken, $info, 60 * 60 * 2);
//        DI()->cache->set("userToken:" . $info['username'], $userToken, 60 * 60 * 2);
        return $userToken;

    }

    public function getByUsername($username) {
        return DI()->cache->get("userToken:" . $username);
    }

    public function getByID($tokenid) {
        return DI()->cache->get("userInfo:" . $tokenid);
    }

    public function remove($tokenid) {
        $info = $this->getByID($tokenid);
        if (!$info) {
            return true;
        }
//        DI()->cache->delete("userToken:" . $info['username']);
        return DI()->cache->delete("userInfo:" . $tokenid) == 1;
    }

    public function refresh($tokenid) {
        $data = $this->getByID($tokenid);
        $this->remove($tokenid);
        return $this->create($data);
    }

    public function check($tokenid) {
        $data = $this->getByID($tokenid);
        if (!$data) {
            DI()->response->setData(null);
            throw new PhalApi_Exception('token失效', 1003);
        };
        return $data;
    }

    public function updatelastlogintime($username) {
        $model = new Model_Admin();
        $rs = $model->updatelastlogintime($username);
        return $rs;

    }

}
